import React from "react";

interface IPoprs {
	name: string;
	getName(name: string): void;
}

interface IStates {
	value: string;
}

class SubAnimal extends React.Component<IPoprs, IStates> {
	name: IPoprs["name"];
	// getName: IPoprs["getName"];
	state: IStates;
	constructor(props: IPoprs) {
		super(props);
		this.name = this.props.name;
		this.state = {
			value: "aa"
		};
		this.changeValue = this.changeValue.bind(this);
	}

	// onClick 事件获取 event
	clickHandle(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
		// 阻止事件冒泡
		// e.stopPropagation()
		console.log(e);
	}

	clickDiv(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {
		// 阻止事件冒泡
		e.stopPropagation();
		console.log("click div");
	}

	// onChange 事件获取 event
	changeValue(e: React.ChangeEvent<HTMLInputElement>) {
		// 这里为什么要这样写,是因为 this.setState() 是一个异步的方法
		// console.log(this.state)直接运行的话,这显示的是上一次的值
		this.setState(
			{
				value: e.target.value
			},
			() => this.props.getName(this.state.value)
		);
	}

	render() {
		return (
			<div>
				<div>The animal name is {this.name}</div>
				<input type="text" onChange={this.changeValue} defaultValue={this.state.value} />
				<button onClick={this.clickHandle}>
					Click me
					{/* <div onClick={this.clickDiv}>点击我会有冒泡</div> */}
				</button>
			</div>

			// <div>The animal name is {this.name}</div>
		);
	}
}

class Animal extends React.Component {
	state: {
		value: string;
	};
	constructor(state: object) {
		super(state);
		this.state = {
			value: "value"
		};
		this.getName = this.getName.bind(this);
	}
	getName(name: string): string {
		console.log(name);
		this.setState({
			value: name
		});
		return name;
	}
	render() {
		return (
			<div>
				<div>Animal {this.state.value}</div>
				<SubAnimal name={"dean"} getName={this.getName} />
			</div>
		);
	}
}

export default Animal;
